package com.mars.foodserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mars.foodserver.entity.Food;
import com.mars.foodserver.entity.FoodCollect;
import com.mars.foodserver.entity.FoodType;
import com.mars.foodserver.mapper.FoodLikeMapper;
import com.mars.foodserver.mapper.FoodMapper;
import com.mars.foodserver.mapper.FoodTypeMapper;
import com.mars.foodserver.request.FoodRequest;
import com.mars.foodserver.response.FoodResponse;
import com.mars.foodserver.response.base.PageInfo;
import com.mars.foodserver.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wq
 * @since 2021-07-19
 */
@Service
public class FoodServiceImpl extends ServiceImpl<FoodMapper, Food> implements IFoodService {

    @Resource
    private FoodTypeMapper foodTypeMapper;

    @Resource
    private IFoodLikeService foodLikeService;

    @Resource
    private IFoodCollectService foodCollectService;


    @Resource
    private IFoodListService foodListService;


    @Resource
    private IFoodMakeWayService foodMakeWayService;

    @Override
    public PageInfo<FoodResponse> page(FoodRequest request) {
        IPage<Food> page = new Page<>(request.getPageNumber(), request.getPageSize());
        LambdaQueryWrapper<Food> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(request.getName())) {
            wrapper.like(Food::getName, request.getName());
        }
        if (Objects.nonNull(request.getType())) {
            if (request.getType() == 1) {
                wrapper.eq(Food::getIsRecommend, 1);
            }
        }
        if (Objects.nonNull(request.getCookType())) {
            wrapper.orderByDesc(Food::getCreateTime);
        } else {
            wrapper.orderByDesc(Food::getUpdateTime);
        }
        // 查询用户收藏的美食
        List<FoodCollect> collectList = foodCollectService.list(new LambdaQueryWrapper<FoodCollect>().eq(FoodCollect::getUserId, request.getUserId()));
        if (!CollectionUtils.isEmpty(collectList)){
            // 获取美食集合
            List<Integer> foodIds = collectList.stream().map(FoodCollect::getFoodId).collect(Collectors.toList());
            // 查询美食信息
            List<Food> foodList = super.list(Wrappers.lambdaQuery(Food.class).in(Food::getId, foodIds));
            // 根据用户收藏的类型 推荐同类型的美食
            List<Integer> foodTypeIds = foodList.stream().map(Food::getFoodTypeId).filter(Objects::nonNull).collect(Collectors.toList());
            wrapper.in(Food::getFoodTypeId,foodTypeIds);
        }

        wrapper.orderByDesc(Food::getCreateTime);
        List<Food> records = baseMapper.selectPage(page, wrapper).getRecords();
        if (!CollectionUtils.isEmpty(records)) {
            List<FoodResponse> list = records.stream().map(x -> {
                FoodResponse response = new FoodResponse();
                BeanUtils.copyProperties(x, response);
                //查询类型名称
                FoodType foodType = foodTypeMapper.selectById(x.getFoodTypeId());
                if (Objects.nonNull(foodType)) {
                    response.setFoodTypeName(foodType.getName());
                }
                response.setIsRecommend(x.getIsRecommend() == 1 ? true : false);
                return response;
            }).collect(Collectors.toList());
            return new PageInfo<>(page.getTotal(), list);
        }
        return null;
    }

    @Override
    public List<FoodResponse> getRecommend(FoodRequest request) {
        List<Food> records = baseMapper.selectList(new LambdaQueryWrapper<Food>()
                .eq(Food::getIsRecommend, 1).orderByDesc(Food::getUpdateTime));
        if (!CollectionUtils.isEmpty(records)) {
            return records.stream().map(x -> {
                FoodResponse response = new FoodResponse();
                BeanUtils.copyProperties(x, response);
                //查询类型名称
                FoodType foodType = foodTypeMapper.selectById(x.getFoodTypeId());
                if (Objects.nonNull(foodType)) {
                    response.setFoodTypeName(foodType.getName());
                }
                return response;
            }).collect(Collectors.toList());
        }
        return null;
    }

    @Override
    public void add(FoodRequest request) {
        Food food = new Food();
        BeanUtils.copyProperties(request, food);
        save(food);
    }

    @Override
    public void publish(Integer userId, FoodRequest request) {
        Food food = new Food();
        BeanUtils.copyProperties(request, food);
        food.setUserId(userId);
        food.setStatus(0);
        save(food);
    }

    @Override
    public List<Food> mineFoods(Integer userId) {
        return baseMapper.selectList(new LambdaQueryWrapper<Food>().
                eq(Food::getUserId, userId).orderByDesc(Food::getCreateTime));
    }

    @Override
    public List<Food> selectBatch(List<Integer> ids) {
        return baseMapper.selectBatchIds(ids);
    }

    @Override
    public void update(FoodRequest request) {
        Food food = new Food();
        BeanUtils.copyProperties(request, food);
        updateById(food);
    }

    @Override
    public void updateStatusDown(Integer foodId) {
        Food food = baseMapper.selectById(foodId);
        food.setStatus(1);
        updateById(food);
    }

    @Override
    public void delete(Integer id) {
        baseMapper.deleteById(id);
    }

    @Override
    public Food detail(Integer id) {
        return baseMapper.selectById(id);
    }

    @Override
    public FoodResponse acquireDetail(Integer userId, Integer id) {
        Food food = baseMapper.selectById(id);
        if (Objects.nonNull(food)) {
            FoodResponse response = new FoodResponse();
            BeanUtils.copyProperties(food, response);
            //查询类型名称
            FoodType foodType = foodTypeMapper.selectById(food.getFoodTypeId());
            if (Objects.nonNull(foodType)) {
                response.setFoodTypeName(foodType.getName());
            }
            boolean likeFood = foodLikeService.isLikeFood(userId, id);
            boolean isCollect = foodCollectService.isCollectFood(userId, id);
            response.setIsLike(likeFood);
            response.setIsCollect(isCollect);
            List<String> foodLists = foodListService.foodList(id);
            if (!CollectionUtils.isEmpty(foodLists)) {
                response.setFoodLists(foodLists);
            }
            List<String> makeWayList = foodMakeWayService.foodMakeWayList(id);
            if (!CollectionUtils.isEmpty(makeWayList)) {
                response.setFoodMakeWays(makeWayList);
            }
            return response;
        }
        return null;

    }

    @Override
    public List<Food> categoryDetailList(Integer foodCategoryId) {
        return baseMapper.selectList(new LambdaQueryWrapper<Food>().eq(Food::getFoodCategoryId, foodCategoryId));
    }

    @Override
    public void updateStatus(Integer id, Integer isRecommend) {
        Food food = baseMapper.selectById(id);
        if (Objects.isNull(food)) {
            throw new RuntimeException("食谱已删除");
        }
        food.setIsRecommend(isRecommend);
        updateById(food);
    }
}
